#!/usr/bin/python3

import os,sys,copy
import sqlite3
from lxml import etree
import urllib.parse
import urllib.request
        
def input_word(wd,mean):
    db1 = sqlite3.connect( os.path.join(os.getcwd(), 'mydict.db') )
    db1.text_factory = str
    cu1 = db1.cursor()
    try:
        cu1.execute( "INSERT OR REPLACE into dict(word, mean) values( ? , ? )", (wd, mean))
    except:
        print('insert error')
    cu1.close()
    db1.commit()
    db1.close()
            
def baidudict(wd):
    res = '拼音：\n'
    n=3
    while n>0:
        try:
            p1 = urllib.parse.urlencode({'wd':wd,'ptype':'zici'})
            url1 = 'http://dict.baidu.com/s?%s' % p1
            opener = urllib.request.build_opener()
            opener.addheaders = [('User-agent', 'Mozilla/5.0')]
            fp1 = opener.open(url1)
            s = fp1.read().decode('utf-8')

            dom = etree.HTML( s )
            pys = dom.xpath('//div[@id="pinyin"]/span/b')
            n=1
            for py in pys:
                res = res+str(n)+'  '+py.text+'\n'
                n+=1
            break
        except:
            n-=1
            res = ''
            continue
    return res
       
